import React, { useState, useEffect } from 'react'
import { Modal, Form, Input, Button, Tabs, message, Row, Col, Alert } from 'antd'
import { PhoneOutlined, SafetyOutlined } from '@ant-design/icons'
import { authService } from '../../api/service'

interface LoginModalProps {
  visible: boolean
  onClose: () => void
  onLoginSuccess: () => void
  closable?: boolean
}

const LoginModal: React.FC<LoginModalProps> = ({
  visible,
  onClose,
  onLoginSuccess,
  closable = true
}) => {
 
  const [loginForm] = Form.useForm()
  const [registerForm] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const [activeTab, setActiveTab] = useState<'login' | 'register'>('login')
  const [countdown, setCountdown] = useState(0)
  const [sendingCode, setSendingCode] = useState(false)
  const [errorMessage, setErrorMessage] = useState<string>('')

  // 倒计时效果
  useEffect(() => {
    if (countdown > 0) {
      const timer = setTimeout(() => setCountdown(countdown - 1), 1000)
      return () => clearTimeout(timer)
    }
  }, [countdown])

  // 发送验证码
  const handleSendCode = async () => {
    try {
      // 根据当前 tab 获取对应表单的手机号
      const currentForm = activeTab === 'login' ? loginForm : registerForm
      const phone = currentForm.getFieldValue('phone')
      
      if (!phone) {
        message.warning('请先输入手机号')
        return
      }
      if (!/^1[3-9]\d{9}$/.test(phone)) {
        message.warning('请输入正确的手机号')
        return
      }

      setSendingCode(true)
      const codeType = activeTab === 'login' ? 'login' : 'register'

      console.log('sendVerificationCode', phone, codeType)
    
      const result = await authService.sendVerificationCode(phone, codeType)
      
      if (result.success) {
        message.success('验证码已发送')
        setCountdown(60)
      } else {
        message.error(result.message || '发送验证码失败')
      }
    } catch (error) {
      message.error('发送验证码失败，请稍后重试')
    } finally {
      setSendingCode(false)
    }
  }

  // 登录
  const handleLogin = async (values: { phone: string; code: string }) => {
    setLoading(true)
    setErrorMessage('') // 清除之前的错误消息
    
    try {
      const result = await authService.loginWithCode(values.phone, values.code)
      console.log('Login result:', result)
      
      if (result.success) {
        message.success('登录成功')
        loginForm.resetFields()
        setCountdown(0)
        setErrorMessage('') // 清除错误消息
        onLoginSuccess()
        onClose()
      } else {
        const errorMsg = result.message || '登录失败'
        console.log('Login error:', errorMsg)
        setErrorMessage(errorMsg) // 设置错误消息
        message.error(errorMsg, 5) // 显示5秒
      }
    } catch (error) {
      console.error('Login exception:', error)
      const errMsg = '登录失败，请稍后重试'
      setErrorMessage(errMsg)
      message.error(errMsg, 5)
    } finally {
      setLoading(false)
    }
  }

  // 注册
  const handleRegister = async (values: { phone: string; code: string }) => {
    setLoading(true)
    setErrorMessage('') // 清除之前的错误消息
    
    try {
      const result = await authService.registerWithCode(values.phone, values.code)
      console.log('Register result:', result)
      
      if (result.success) {
        const successMsg = result.message || '注册成功，请登录'
        console.log('Show success message:', successMsg)
        message.success(successMsg)
        registerForm.resetFields()
        setCountdown(0)
        setErrorMessage('') // 清除错误消息
        // 切换到登录tab
        setActiveTab('login')
      } else {
        const errorMsg = result.message || '注册失败'
        console.log('Show error message:', errorMsg)
        setErrorMessage(errorMsg) // 设置错误消息
        message.error(errorMsg, 5) // 显示5秒
      }
    } catch (error) {
      console.error('Register exception:', error)
      const errMsg = '注册失败，请稍后重试'
      setErrorMessage(errMsg)
      message.error(errMsg, 5)
    } finally {
      setLoading(false)
    }
  }

  const handleCancel = () => {
    loginForm.resetFields()
    registerForm.resetFields()
    setCountdown(0)
    setErrorMessage('')
    onClose()
  }

  // 表单公共部分
  const renderFormItems = () => (
    <>
      <Form.Item
        name="phone"
        label="手机号"
        rules={[
          { required: true, message: '请输入手机号' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
        ]}
      >
        <Input
          prefix={<PhoneOutlined />}
          placeholder="请输入手机号"
          maxLength={11}
        />
      </Form.Item>
      
      <Form.Item
        label="验证码"
        required
      >
        <Row gutter={8}>
          <Col span={14}>
            <Form.Item
              name="code"
              noStyle
              rules={[
                { required: true, message: '请输入验证码' },
                { pattern: /^\d{6}$/, message: '请输入6位验证码' }
              ]}
            >
              <Input
                prefix={<SafetyOutlined />}
                placeholder="请输入验证码"
                maxLength={6}
              />
            </Form.Item>
          </Col>
          <Col span={10}>
            <Button
              block
              disabled={countdown > 0}
              loading={sendingCode}
              onClick={handleSendCode}
            >
              {countdown > 0 ? `${countdown}秒后重试` : '发送验证码'}
            </Button>
          </Col>
        </Row>
      </Form.Item>
    </>
  )

  const tabItems = [
    {
      key: 'login',
      label: '登录',
      children: (
        <Form
          form={loginForm}
          name="login"
          onFinish={handleLogin}
          layout="vertical"
          size="large"
        >
          {renderFormItems()}
          
          {/* 错误消息提示 */}
          {errorMessage && activeTab === 'login' && (
            <Form.Item>
              <Alert
                message={errorMessage}
                type="error"
                showIcon
                closable
                onClose={() => setErrorMessage('')}
                style={{ marginBottom: 16 }}
              />
            </Form.Item>
          )}
          
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
              style={{ background: '#fe2c55', borderColor: '#fe2c55' }}
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      )
    },
    {
      key: 'register',
      label: '注册',
      children: (
        <Form
          form={registerForm}
          name="register"
          onFinish={handleRegister}
          layout="vertical"
          size="large"
        >
          {renderFormItems()}
          
          {/* 错误消息提示 */}
          {errorMessage && activeTab === 'register' && (
            <Form.Item>
              <Alert
                message={errorMessage}
                type="error"
                showIcon
                closable
                onClose={() => setErrorMessage('')}
                style={{ marginBottom: 16 }}
              />
            </Form.Item>
          )}
          
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
              style={{ background: '#fe2c55', borderColor: '#fe2c55' }}
            >
              注册
            </Button>
          </Form.Item>
        </Form>
      )
    }
  ]

  return (
    <Modal
      title="用户登录"
      open={visible}
      onCancel={closable ? handleCancel : undefined}
      footer={null}
      width={400}
      centered
      destroyOnClose
      closable={closable}
    >
      <Tabs
        activeKey={activeTab}
        onChange={(key) => {
          setActiveTab(key as 'login' | 'register')
          // 切换tab时清除两个表单
          loginForm.resetFields()
          registerForm.resetFields()
          setCountdown(0)
          setErrorMessage('') // 切换tab时清除错误消息
        }}
        items={tabItems}
        centered
      />
    </Modal>
  )
}

export default LoginModal